package com.bocai.dahuatech.ui.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.bocai.dahuatech.Bean.BaseBean;
import com.bocai.dahuatech.Bean.LoginBean;
import com.bocai.dahuatech.Bean.PersonInfoBean;
import com.bocai.dahuatech.R;
import com.bocai.dahuatech.base.BaseActivity;
import com.bocai.dahuatech.utils.AESUtils;
import com.bocai.dahuatech.utils.SharePrefencesUtil;
import com.google.gson.Gson;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class   LoginActivity extends BaseActivity implements View.OnClickListener
{

    @Bind(R.id.iv_login_finish)
    ImageView ivFinish;
    @Bind(R.id.tv_login_try)
    TextView tvTry;
    @Bind(R.id.tv_toregist)
    TextView tvToRegist;
    @Bind(R.id.rb_personal)
    RadioButton rbPersonal;
    @Bind(R.id.rb_distributor)
    RadioButton rbDistributor;
    @Bind(R.id.tv_toregist_fxs)
    TextView tvToRegistFXS;
    @Bind(R.id.tv_forgetpsd)
    TextView tvForgetPsd;
    @Bind(R.id.btn_login)
    Button btnLogin;
    @Bind(R.id.et_regist_name)
    EditText etName;
    @Bind(R.id.et_regist_password)
    EditText etPwd;
    @Bind(R.id.cb_login_rememberpsd)
    CheckBox cbRemember;
    boolean isPerson=true;
    PersonInfoBean bean=new PersonInfoBean();
    LoginBean loginbean;
    boolean isRemember=true;
    boolean isLogin;
    String  ifpromotion="false";//False不可查看  true可查看
    private SharedPreferences preferences;
    @Override
    protected int contentView()
    {
        return R.layout.activity_login;
    }

    @Override
    protected void initView()
    {
        ButterKnife.bind(this);
        isLogin=getIntent().getBooleanExtra("tologin", true);
        if(isLogin)
        {
            tvTry.setVisibility(View.VISIBLE);
            ivFinish.setVisibility(View.GONE);
        }else
        {
            tvTry.setVisibility(View.GONE);
            ivFinish.setVisibility(View.VISIBLE);
        }
        initEvent();
    }

    @Override
    protected void initEvent()
    {
        ivFinish.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                finish();
            }
        });
        if(SharePrefencesUtil.getCount(this)==1)
        {
            cbRemember.setChecked(true);
        }else
        {
            cbRemember.setChecked(SharePrefencesUtil.getIsRememberPsd(this));
            isRemember=SharePrefencesUtil.getIsRememberPsd(this);
            etName.setText(SharePrefencesUtil.getuser_name(this));
            etPwd.setText(SharePrefencesUtil.getPsd(this));
        }
        cbRemember.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
        {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
            {
                isRemember=isChecked;
            }
        });
        tvTry.setOnClickListener(this);
        btnLogin.setOnClickListener(this);
        tvToRegist.setOnClickListener(this);
        tvToRegistFXS.setOnClickListener(this);
        tvForgetPsd.setOnClickListener(this);

    }
    Observer<BaseBean> observer=new Observer<BaseBean>()
    {

        @Override
        public void onCompleted()
        {
        }

        @Override
        public void onError(Throwable e)
        {
            Log.e("basebean",e.toString());
            hideLoading();
            showToast(R.string.neterror);
        }

        @Override
        public void onNext(BaseBean baseBean)
        {
            hideLoading();
            if("1".equals(baseBean.getReturnNo()))
            {
                ifpromotion=baseBean.getReturnInfo().toLowerCase();
                String result=AESUtils.decode(baseBean.getContent());
                result=start+result+end;
                Log.e("result", result);
                Gson gson=new Gson();
                loginbean= gson.fromJson(result, LoginBean.class);
                SharedPreferences preferences=getSharedPreferences("user",MODE_PRIVATE);
                SharedPreferences.Editor editor=preferences.edit();
                editor.putString("user_name",etName.getText().toString());
                editor.putString("password", etPwd.getText().toString());
                editor.putInt("fid", loginbean.getContent().get(0).getFID());
                editor.putString("user_id", loginbean.getContent().get(0).getFUserID());
                editor.putString("FUserName",loginbean.getContent().get(0).getFUserName());
                editor.putString("customerCode", loginbean.getContent().get(0).getFCustomerCode());
                editor.putString("customerName", loginbean.getContent().get(0).getFCustomerName());
                editor.putInt("FAccessFlag", loginbean.getContent().get(0).getFAccessFlag());
                editor.putBoolean("isremember", isRemember);
                editor.putString("ifpromotion",ifpromotion);
                editor.putInt("count", 2);
                editor.commit();
                getInfo();
            }else
            {
                showError(baseBean.getReturnInfo().toString());
            }
        }
    };

    Observer<BaseBean> infoObserver=new Observer<BaseBean>()
    {

        @Override
        public void onCompleted()
        {
            if(isLogin)
            {
//             特定的分销商在特定的时间在第一次登录成功后跳转到促销大会界面，其他情况正常跳转到主界面
                preferences = getSharedPreferences("user",MODE_APPEND);
                int count = preferences.getInt("firstpro", 0);
//                if(count==0&&"true".equals(ifpromotion.toLowerCase()))
                if("true".equals(ifpromotion.toLowerCase()))
                {
                    startActivity(new Intent(LoginActivity.this, PromotionActivity.class));
                    LoginActivity.this.finish();
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putInt("firstpro", ++count);
                    editor.commit();
                }else
                {
                    startActivity(new Intent(LoginActivity.this, HomeActivity.class));
                    LoginActivity.this.finish();
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putInt("firstpro", ++count);
                    editor.commit();
                }
            }else
            {
                //游客未登录时跳转进登录页面登录成功后登录页面finish，不做任何跳转
                LoginActivity.this.finish();
            }
        }

        @Override
        public void onError(Throwable e)
        {
            Log.e("erro", e.toString());
            showToast(R.string.neterror);
            hideLoading();
        }

        @Override
        public void onNext(BaseBean baseBean)
        {
            hideLoading();
            if("1".equals(baseBean.getReturnNo()))
            {
                String result= AESUtils.decode(baseBean.getContent());
                Log.e("result",result);
                bean=new Gson().fromJson(result, PersonInfoBean.class);
                SharedPreferences preferences=getSharedPreferences("user",MODE_PRIVATE);
                SharedPreferences.Editor editor=preferences.edit();
                editor.putString("Province", bean.getProvince());
                editor.putString("City", bean.getCity());
                editor.putString("Area", bean.getArea());
                editor.putString("phone",bean.getPhone());
                editor.putString("companyName",bean.getPhone());
                editor.putInt("Provinceid", bean.getProvinceId());
                editor.commit();
            }else
            {
                showError(baseBean.getReturnInfo());
            }
        }
    };

    /**
     * 获取会员信息
     */
    private void getInfo()
    {
        getTestApi().getPersonInfo(loginbean.getContent().get(0).getFID())
                .compose(this.<BaseBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(infoObserver);
    }
    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            //试用
            case R.id.tv_login_try:
                SharedPreferences preferences=getSharedPreferences("user",MODE_PRIVATE);
                SharedPreferences.Editor editor=preferences.edit();
                editor.putInt("FAccessFlag",0);
                editor.commit();
                startActivity(new Intent(LoginActivity.this, HomeActivity.class));
                LoginActivity.this.finish();
                break;
            case R.id.tv_toregist:
                Intent intent=new Intent(this,RegistPersonalActivity.class);
                intent.putExtra("what","person");
                startActivity(intent);
                break;
            case R.id.tv_toregist_fxs:
                Intent intent1=new Intent(this,RegistPersonalActivity.class);

                intent1.putExtra("what","distributor");
                startActivity(intent1);
                break;
            case R.id.tv_forgetpsd:
                startActivity(new Intent(this,ForgetPsdActivity.class));
                break;
            case R.id.btn_login:
                String name=etName.getText().toString();
                String pwd=AESUtils.md5(etPwd.getText().toString());
                Log.e("psd",pwd);
                if(TextUtils.isEmpty(etName.getText().toString()))
                {
                    showToast(R.string.usernamenotnull);
                }else if(TextUtils.isEmpty(etPwd.getText().toString()))
                {
                    showToast(R.string.psdnotnull);
                }else
                {
                    showLoading();
                    getTestApi().login(name,etPwd.getText().toString(),"Android")
                            .compose(this.<BaseBean>bindToLifecycle())
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(observer);
                }
//
                break;
        }
    }
}
